package com.xiaozhi.xzadmin.controller.system;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileWriter;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaozhi.xzadmin.config.Aop.AopLogger;
import com.xiaozhi.xzadmin.config.Aop.AopUserOnline;
import com.xiaozhi.xzadmin.pojo.AjaxResult;
import com.xiaozhi.xzadmin.pojo.CommonUtil;
import com.xiaozhi.xzadmin.pojo.system.Logininfor;
import com.xiaozhi.xzadmin.pojo.system.SystemFile;
import com.xiaozhi.xzadmin.service.sys.SysFileService;
import com.xiaozhi.xzadmin.tools.StringUtil;
import com.xiaozhi.xzadmin.tools.web.BaseController;
import net.sf.jsqlparser.Model;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.soap.Addressing;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @Author: zhangxiaozhi
 * @Description: 1.0
 * @Date: create in 2022/3/19 23:01
 */
@Controller
@RequestMapping("/system/file/")
@SaCheckLogin
public class Sys_fileController extends BaseController {
    @Autowired
    private SysFileService sysFileService;

    String path = new CommonUtil().getFilepath();

    /**
     * 文件管理页
     */
    @AopUserOnline
    @GetMapping("main")
    public String main() {
        return "/system/file/main";
    }
    /**
     * 文件上传页
     */
    @AopUserOnline
    @GetMapping("add")
    public String fileadd() {
        return "/system/file/add";
    }

    /**
     * 文件上传接口
     */
    @AopUserOnline
    @PostMapping("/upload")
    @ResponseBody
    @SaCheckPermission("file:view")
    public AjaxResult fileupload(@RequestParam("file") MultipartFile[] file) throws IOException {
        if (file!=null){
            for (MultipartFile files : file) {

                SystemFile systemFile = new SystemFile();
//                文件真实名称
                String filename = files.getOriginalFilename();
                systemFile.setFileRealName(filename);
//                文件类型
                String filetype = FilenameUtils.getExtension(filename).toLowerCase();
                systemFile.setFileType(filetype);
//                文件名
                String newfilename = String.valueOf(UUID.randomUUID());
                systemFile.setFileName(newfilename);
//                文件大小
                Double size = Double.valueOf(files.getSize()) / 1024.0;
                String filesize =  size+ "k";
                systemFile.setFileSize(filesize);
//                文件路径
                systemFile.setFilePath(path);
                //创建人
                systemFile.setCreateBy(StpUtil.getLoginIdAsString());
                String newfile=null;
                if ("".equals(filetype)){
                    newfile = newfilename;
                }else {
                    newfile = newfilename+"."+filetype;
                }

                //保存文件
                File localFile = new File(path + newfile);
                files.transferTo(localFile);
                //数据入库
                sysFileService.insetsystemFile(systemFile);
            }
        }

        return success("上传成功");
    }


    /***
     * 文件查询
     * @page 页码
     * @limit 页码长度
     * @systemFile systemFile实体类
     * @return
     */
    @AopUserOnline
    @AopLogger(title = "文件日志",type = 0)
    @SaCheckPermission("file:view")
    @RequestMapping("/data")
    @ResponseBody
    public AjaxResult filequery(@RequestParam(value = "page", required = false,defaultValue = "1")Integer  page,
                          @RequestParam(value = "limit", required = false,defaultValue = "5")Integer limit,
                           SystemFile systemFile){
        Page<SystemFile> filePage = sysFileService.getSystemFilePage(page,limit,systemFile);
        return success(filePage);
    }

    /***
     * 文件下载
     * @fileName fileName文件名
     * @fileType 文件类型
     * @fileRealName 文件真实名
     * @return
     */
    @AopUserOnline
    @AopLogger(title = "文件日志",type = 0)
    @SaCheckPermission("file:view")
    @RequestMapping(value ="/download/{fileName}/{fileType}/{fileRealName}")
    public ResponseEntity<byte[]> download(@PathVariable String fileName,
                                           @PathVariable String fileType,
                                           @PathVariable String fileRealName) throws IOException {
        File file;
        if ("".equals(fileName) || fileName ==null){
            return null;
        }
        file = new File(path+fileName+"."+fileType);
        if ("".equals(fileType) || fileType ==null){
            //新建一个文件
            file = new File(path+fileName);
        }
        byte[] body = null;
        InputStream is = new FileInputStream(file);
        body = new byte[is.available()];
        is.read(body);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attchement;filename=" + fileRealName);
        HttpStatus statusCode = HttpStatus.OK;
        ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
        return entity;
    }

    /***
     * 文件信息删除
     * @return
     */
    @AopUserOnline
    @AopLogger(title = "文件日志",type = 3)
    @SaCheckPermission("file:view")
    @RequestMapping("/remove")
    @ResponseBody
    public AjaxResult removeSystemFile(@RequestBody Map<String,String> map) {
        String userid = map.get("id");
        ArrayList<String> strings = StringUtil.cutString(userid);
        List<SystemFile> systemlist = sysFileService.getSystemFileByid(strings);
        Boolean flag = sysFileService.delSystemFileByid(strings);
        if (flag){
            for (int i = 0; i < systemlist.size(); i++) {
                if (systemlist.get(i).getFileType() !=null || "".equals(systemlist.get(i).getFileType())){
                    FileUtil.del(path+systemlist.get(i).getFileName()+"."+systemlist.get(i).getFileType());
                }else {
                    FileUtil.del(path+systemlist.get(i).getFileName());
                }
            }
            return success("删除成功");
        }
        return error("删除失败");
    }
}
